Vue.component('yl-goods', {
  template: `<el-dialog id="ylGoods"  title="商品选择" :visible.sync="visibleDialog" width="80vw">
      <el-form :inline="true" :form="form">
          <el-form-item>
            <el-input v-model.trim="Article_Name" clearable placeholder="请输入商品名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model.trim="selectSupplier" collapse-tags multiple style="width: 100%;" clearable placeholder="筛选供应商">
              <el-option v-for="item in supplier" :key="item.Supplier_SerialNumber" :label="item.Supplier_Name" :value="item.Supplier_SerialNumber"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
              <el-cascader v-model="selectclassify" filterable collapse-tags clearable placeholder="分类汇总"
                  :props="defaultProps" :options="classify" style="width: 300px"></el-cascader>
          </el-form-item>
          <el-form-item>
              <el-button type="success" @click="onSerach">查询</el-button>
          </el-form-item>
      </el-form>
      <el-table :data="tableData.slice((form.page-1)*form.limit,form.page*form.limit)" :row-key="row=>row.Supplier_Article_SerialNumber"  stripe border height="50vh" style="width: 100%"  @selection-change="handleSelectionChange">
          <el-table-column type="selection" :reserve-selection="true" width="50"></el-table-column>
          <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
          <el-table-column align="center" prop="Article_Specifications_SerialNumber" show-overflow-tooltip label="供应商品内码"></el-table-column>
          <el-table-column align="center" prop="Supplier_Name" show-overflow-tooltip label="供应商名称"></el-table-column>
          <el-table-column align="center" prop="Article_Name" show-overflow-tooltip label="商品名称"></el-table-column>
          <el-table-column align="center" prop="Specifications_Name" show-overflow-tooltip label="规格名称"></el-table-column>
          <el-table-column align="center" prop="Picture_URL" width="140" align="center" label="商品封面">
              <template v-slot="{row}">
                  <el-image fit="contain" :src="BASE_IMG + row.Picture_URL" style="width:100px;height: 100px;"></el-image>
              </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
              <template v-slot="{row,$index}">
                  <el-button size="small" :disabled="loading" type="danger" @click="handleRemove($index)">删除</el-button>
              </template>
          </el-table-column>
      </el-table>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="form.page" :page-sizes="[10, 30 , 60 ,100, 200, 300, 400]" :page-size="form.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
          <el-button @click="$emit('update:visible',false)">取消</el-button>
          <el-button type="primary" @click="submit()">确定</el-button>
      </span>
  </el-dialog>`,
  props: ['data', 'visible'],
  data() {
    return {
      visibleDialog: false,
      tableData: [],//详情
      form: {
        SQLSerialNumber: "A_business_supplier_article3",
        Condition: '',
        ExtensionCondition: '',
        page: 1,
        limit: 10,
      },
      total: 0,
      activeName: "1",
      loading: false,
      supplier: [],//全部品牌
      classify: [],//全部类别
      screen: [{
        label: '相同商品取采购价格最低',
        value: '0'
      }, {
        label: '相同商品取采购价格最高',
        value: '1'
      }],
      selectSupplier: [],//已选品牌
      selectclassify: [],//已选分类
      Article_Name: '',//商品名称
      defaultProps: {
        children: 'Children',
        label: 'Classify_Name',
        value: 'Classify_SerialNumber',
        multiple: true,
      },
      multipleSelection: [],
    }
  },
  watch: {
    visible() {
      this.visibleDialog = this.visible
    },
    visibleDialog(val) {
      this.$emit('update:visible', val);
    },
  },
  methods: {
    onSerach() {
      let classify = []
      this.selectclassify.forEach(item => {
        classify = uniqueArr([...classify, ...item]);
      })
      let sql = " and business_article_info.Article_Name LIKE '%" + this.Article_Name + "%'\r\n";
      //去重
      if (classify.length > 0) {
        let str = "";
        classify.forEach((item, index) => {
          if (index == 0) {
            str = "business_article_classify.Classify_SerialNumber = '" + item + "' \r\n"
          } else {
            str = str + " or business_article_classify.Classify_SerialNumber = '" + item + "' \r\n"
          }
        })
        sql = sql + "and (" + str + ")\r\n"
      }
      if (this.selectSupplier.length > 0) {
        let str = "";
        this.selectSupplier.forEach((item, index) => {
          if (index == 0) {
            str = "business_supplier_info.Supplier_SerialNumber = '" + item + "' \r\n"
          } else {
            str = str + " or business_supplier_info.Supplier_SerialNumber = '" + item + "' \r\n"
          }
        })
        sql = sql + "and (" + str + ")\r\n"
      }
      this.form.ExtensionCondition = window.btoa(unescape(encodeURIComponent(sql)))
      this.getList(this.form);
    },
    handleSizeChange(val) {
      this.form.page = 1;
      this.form.limit = val;
    },
    handleCurrentChange(val) {
      this.form.page = val;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleRemove(index) {
      this.tableData = this.tableData.filter((i, id) => id != (this.form.page - 1) * this.form.limit + index)
    },
    getList(data) {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryBySQLSerialNumber`,
        type: 'POST',
        data,
        success: function (Result) {
          that.tableData = Result;
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json"
      });
    },
    submit() {
      if (this.multipleSelection.length > 0) {
        this.$emit('success', this.multipleSelection);
        this.$emit('update:visible', false)
      } else {
        this.$message({
          message: '请先选择商品',
          type: 'warning'
        })
      }
    },
    getData() {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalQueryByTableName`,
        type: 'POST',
        data: {
          Data: 'business_supplier_info',
          Condition: "Row_Status='0'",
        },
        success: function (res) {
          that.supplier = res;
        },
        complete: function (XMLHttpRequest) {
          that.loading = false
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json"
      });
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/getAllClassify`,
        type: 'GET',
        success: function (data) {
          that.classify = data
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json"
      });
    }
  },
  mounted() {
    this.getData();
  },
})
new Vue({
  el: '#app',
  data() {
    return {
      form: [],
      loading: false,
      dialogVisible: false,
      Store_SerialNumber:'',
    }
  },
  mounted() {
    if (getCookie('role')) {
      let roleObj = JSON.parse(getCookie('role'));
      this.Store_SerialNumber = roleObj.other;
    }
  },
  methods: {
    getArticle(data) {
      data.forEach(item => {
        item.Quantity = 100
      })
      this.form = data;
      console.log(data);
    },
    submitUpload(i = 0) {
      const that = this;
      if (i < this.form.length) {
        this.loading = true;
        //1.查询店铺库存有无该商品
        //2.有的话,修改 ,没有的话添加
        $.ajax({
          headers: requestHeaders(),
          url: `${BASE_URL2}/generalBusiness/generalQueryByTableNameWithOriginal`,
          type: 'POST',
          data: {
            Data: 'business_store_inventory',
            Condition: "Row_Status='0' AND Supplier_Article_SerialNumber='" + that.form[i].Supplier_Article_SerialNumber + "'",
          },
          success: function (res) {
            let data = {};
            if (res.length == 0) {//没有商品,首次添加
              let business_store_inventory = [{
                Store_Inventory_SerialNumber: '',
                Store_SerialNumber: that.Store_SerialNumber,
                Supplier_Article_SerialNumber: that.form[i].Supplier_Article_SerialNumber,
                Total_Stock: that.form[i].Quantity,
                Stock_Remain: that.form[i].Quantity,
                Stock_Sell: 0,
              }]
              data = { Add: { business_store_inventory }}
            } else {//有该商品,修改库存
              res[0].Total_Stock = accAdd(res[0].Total_Stock,that.form[i].Quantity);
              res[0].Stock_Remain = accAdd(res[0].Stock_Remain,that.form[i].Quantity);
              data = { Modify: { business_store_inventory:res }}
            }
            that.submitForm({ Data: JSON.stringify(data) }, (res) => {
              that.submitUpload(i + 1);
            })
          },
          error: function () {
            that.$message.error("操作失败，请稍后再试")
          },
          complete: function (XMLHttpRequest) {
            requestPretreatment(XMLHttpRequest);
          },
          dataType: "json"
        });
      } else if (i != 0) {
        this.loading = false;
        this.$message.success("入库结束")
        window.history.go(-1)
      }
    },
    submitForm(data, callback) {
      $.ajax({
        headers: requestHeaders(),
        url: `${BASE_URL2}/generalBusiness/generalSave`,
        type: 'POST',
        data,
        success: function (res) {
          callback(res)
        },
        complete: function (XMLHttpRequest) {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json"
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

  }
})